// @Name    : login_page
// @author  : simon
// @date    : 2023/10/13 11:24
// @desc :
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:zx_flutter_network_manager/zx_flutter_network_manager.dart';
import 'zx_text_field.dart';
import 'cai_loading_dialog.dart';
import 'cai_no_constraints_elevated_button.dart';
import 'cai_no_constraints_icon_button.dart';
import 'cai_toast.dart';


// 在Row或者Column中，如果元素会越界显示内容。
// 则考虑应用一个伸缩因子(例如，使用一个扩展的小部件)来强制RenderFlex的子元素适应可用空间，而不是按其自然大小调整大小。

class RukLoginPage extends StatefulWidget {
  const RukLoginPage({super.key});

  @override
  State<RukLoginPage> createState() => _RukLoginPageState();
}

class _RukLoginPageState extends State<RukLoginPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _serController = TextEditingController();
  final TextEditingController _portCodeController = TextEditingController();

  final TapGestureRecognizer _tapAgreementPreRecognizer =
      TapGestureRecognizer();
  final TapGestureRecognizer _tapPressRecognizer = TapGestureRecognizer();
  final TapGestureRecognizer _tapAccountRecognizer = TapGestureRecognizer();
  bool _isAgreeProtocol = false;
  bool _isRememberAccount = true;

  PackageInfo? _packageInfo;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _phoneController.text = '13300000000';
    _serController.text = 'RUKqwe!@#';
    _portCodeController.text = '9910';

    _tapPressRecognizer.onTap = _handlePress;
    _tapAgreementPreRecognizer.onTap = _handlePressAgreementPre;
    _tapAccountRecognizer.onTap = _handleAccount;
    fetchInfoData();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _serController.dispose();
    _portCodeController.dispose();
    _tapPressRecognizer.dispose();
    _tapAgreementPreRecognizer.dispose();
    _tapAccountRecognizer.dispose();
    super.dispose();
  }

  Future<void> fetchInfoData() async {
    try {
      dynamic response = await Future.wait([
        PackageInfo.fromPlatform(),
      ]);
      if (!mounted) {
        return;
      }
      setState(() {
        _packageInfo = response;
      });
    } catch (e) {
      return;
    }
  }

  void _handlePress() {
    // Map<String,dynamic>  arg = {'defaultTitle': '服务协议', 'url': HttpDefine.httpServiceUrl};
    // Navigator.pushNamed(context, CaiRukRoutesConstant.flutterWebViewPage,
    //     arguments: arg);
    // context.push(CaiRukRoutesConstant.flutterWebViewPage,extra: arg);
  }

  void _handlePressAgreementPre() {
    setState(() {
      _isAgreeProtocol = !_isAgreeProtocol;
    });
  }

  void _handleAccount() {
    setState(() {
      _isRememberAccount = !_isRememberAccount;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //默认是true，改为false之后，键盘就不会遮挡溢出报错。
      resizeToAvoidBottomInset: false,
      backgroundColor: const Color(0xff303747),
      body: SafeArea(
        child: bodyContainer(),
      ),
    );
  }

  Widget bodyContainer() {
    return SizedBox(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          logoWidget,
          dividerContainerWidget,
          cardContainerWidget,
          const Expanded(
            child: SizedBox(),
          ),
          versionWidget,
        ],
      ),
    );
  }

  Widget get logoWidget {
    return Container(
      margin: EdgeInsets.only(top: 30.w),
      child: Icon(Icons.local_activity,size: 100.w,),
    );
  }

  Widget get dividerContainerWidget {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 15.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 50.w,
            child: Divider(
              endIndent: 5.w,
              color: Colors.white,
            ),
          ),
          Text(
            '5G智慧云生产/财务/物流/库存系统',
            style: TextStyle(fontSize: 13.sp, color: Colors.white),
          ),
          SizedBox(
            width: 50.w,
            child: Divider(
              indent: 5.w,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  ///自适应内容高度
  Widget get cardContainerWidget {
    return Container(
      margin: EdgeInsets.fromLTRB(20.w, 10.w, 20.w, 0),
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.w),
      ),
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(top: 20.w),
            child: Text(
              '登录',
              style: TextStyle(
                  fontSize: 22.sp,
                  color: const Color(0xff333333),
                  fontWeight: FontWeight.bold),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.w),
            child: ZXCustomTextField(
              height: 44.w,
              hintText: '请输入手机号',
              inputFormatters: [LengthLimitingTextInputFormatter(11)],
              controller: _phoneController,
              keyboardType: TextInputType.number,
              // autofocus: true,
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.w),
            child: ZXCustomTextField(
              height: 44.w,
              hintText: '请输入密码',
              obscureText: true,
              showObscureTextEye: true,
              controller: _serController,
              keyboardType: TextInputType.url,
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.w),
            child: ZXCustomTextField(
                height: 44.w,
                hintText: '请输入企业码',
                controller: _portCodeController,
                keyboardType: TextInputType.url),
          ),
          Padding(
              padding: EdgeInsets.only(top: 20.w),
              child: CaiNoConstraintsElevatedButton(
                fixedSize: Size(double.infinity, 44.w),
                onPressed: loginAction,
                child: Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 17.sp,
                    color: Colors.white,
                  ),
                ),
              )),
          Padding(
            padding: EdgeInsets.only(top: 5.w),
            child: rememberContainerWidget(),
          ),
          Container(
            // color: Colors.orange,
            child: agreementContainerWidget(),
          ),
        ],
      ),
    );
  }

  Widget rememberContainerWidget() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        CaiNoConstraintsIconButton(
            buttonSize: Size(30.w, 30.w),
            icon:Icon(_isRememberAccount ?Icons.check_circle:Icons.check_circle_outline_sharp,weight: 15.w,),
            style: IconButton.styleFrom(),
            onPressed: () {
              setState(() {
                _isRememberAccount = !_isRememberAccount;
              });
            }),
        Text.rich(TextSpan(
          text: '记住账户',
          style: TextStyle(color: const Color(0xff333333), fontSize: 12.sp),
          recognizer: _tapAccountRecognizer,
        )),
        const Expanded(child: SizedBox()),
      ],
    );
  }

  Widget agreementContainerWidget() {
    return Padding(
      padding: EdgeInsets.only(bottom: 5.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CaiNoConstraintsIconButton(
              buttonSize: Size(30.w, 30.w),
              style: IconButton.styleFrom(
                  alignment: Alignment.topCenter,
                  padding: EdgeInsets.only(top: 2.w)),
              icon:Icon(_isAgreeProtocol ?Icons.check_circle:Icons.check_circle_outline_sharp,weight: 15.w,),
              onPressed: () {
                setState(() {
                  _isAgreeProtocol = !_isAgreeProtocol;
                });
              }),
          Expanded(
              child: Text.rich(
            TextSpan(
                recognizer: _tapAgreementPreRecognizer,
                text: '我已认真阅读、理解并同意',
                style:
                    TextStyle(color: const Color(0xff333333), fontSize: 12.sp),
                children: [
                  TextSpan(
                      text: '《瑞利时平台服务协议》',
                      style: TextStyle(
                          color: const Color(0xff3781CA), fontSize: 12.sp),
                      recognizer: _tapPressRecognizer)
                ]),
          ))
        ],
      ),
    );
  }

  Widget get versionWidget {
    return Text(
      'V${_packageInfo?.version ?? ''}(${_packageInfo?.buildNumber ?? ''})',
      style: TextStyle(color: Colors.white, fontSize: 10.sp),
    );
  }

  void loginAction() async {
    if (_phoneController.text.isEmpty || _serController.text.isEmpty) {
      CAIToast.showToast('请输入有效的账号和密码');
      return;
    }
    if (_portCodeController.text.isEmpty) {
      CAIToast.showToast('请输入企业码');
      return;
    }
    if (!_isAgreeProtocol) {
      CAIToast.showToast('请阅读并勾选同意服务协议');
      return;
    }
    if (!mounted) return;
    CAILoadingDialog.showLoading(context);
    try {
      Map map = {
        'cellphone': _phoneController.text,
        // 'password': _serController.text,
        'password2': '1',
      };
      final value = await CaiHttpRequest.postRequest('/v1/logistics/driver/login',data: map);
      CAILoadingDialog.hide();
      await loginSuccess(value);
    } catch (e) {
      CAILoadingDialog.hide();
    }
  }

  Future<void> loginSuccess(Map<String, dynamic> value) async {

     CAIToast.showToast('登录成功');
  }
}
